/* eslint-disable react-hooks/exhaustive-deps */
/*
 * @Author: 周海 zhouhaib@yonyou.com
 * @Date: 2022-12-17 11:45:37
 * @LastEditors: zhouhai zhouhaib@yonyou.com
 * @LastEditTime: 2024-10-23 17:55:42
 */
/* eslint-disable jsx-a11y/anchor-is-valid */
import React, { useEffect, useRef, useState } from 'react'
import { message, Popconfirm } from 'antd';
import { SysUserOnlineDomain } from '@/type.d/monitor/online';
import ResizeTable from '@/components/ResizeTable';
import { pageInfo } from '@/type.d/ajaxResult';
import PageDiv from '@/components/PageDiv';
import { useStore } from '@/store';
import {
    ActionType,
    ProColumns,
    ProFormInstance,
    ProFormText,
    QueryFilter,
} from '@ant-design/pro-components';


import './index.less';
import { forceLogout, listOnline } from '@/api/monitor/online';

const Online: React.FC = () => {
    const { layoutStore } = useStore();

    const actionRef = useRef<ActionType>();
    const queryformRef = useRef<ProFormInstance<SysUserOnlineDomain>>();
    const [tableListDataSource, setTableListDataSource] = useState<SysUserOnlineDomain[]>([]);

    const [pageInfo, setPageInfo] = useState<pageInfo>({
        current: 1,
        pageSize: 10,
        total: 0
    });



    /**
     * 列表字段配置
     */
    const columns: ProColumns<SysUserOnlineDomain>[] = [
        {
            dataIndex: 'index',
            valueType: 'indexBorder',
            width: 48,
        },
        {
            title: '会话编号',
            dataIndex: 'tokenId',
            valueType: 'text',
            align: 'left',
            width: '50',
            ellipsis: true
        },
        {
            title: '登录名称',
            dataIndex: 'userName',
            valueType: 'select',
            align: 'left',
            width: '50',
        },
        {
            title: '主机',
            dataIndex: 'ipaddr',
        },
        {
            title: '登录地点',
            dataIndex: 'loginLocation',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '浏览器',
            dataIndex: 'browser',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '操作系统',
            dataIndex: 'os',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '登录时间',
            dataIndex: 'loginTime',
            valueType: 'dateTime',
            align: 'left',
            width: '50',
        },
        {
            title: '操作',
            width: 180,
            key: 'option',
            valueType: 'option',
            render: (_dom: React.ReactNode, entity: SysUserOnlineDomain) => [
                <Popconfirm title={`是否确认强退名称为"${entity.userName}"的用户？`} okText="是" cancelText="否" onConfirm={() => {
                    onForceLogout(entity.tokenId)
                }}>
                    <a key="delete">强退</a>
                </Popconfirm>

            ],
        },

    ];

    const onForceLogout = (tokenId: string) => {
        layoutStore.OpenSpanning()
        forceLogout(tokenId).then(() => {
            message.success('强退成功！')
            const _data = queryformRef?.current?.getFieldsValue()
            onQuery({ ...pageInfo, ..._data })
        }).finally(() => {
            layoutStore.CloseSpanning()
        })

    }

    //监听分页得操作
    useEffect(() => {
        if (pageInfo.total > 0) {
            //如果原页面有数据，触发查询
            const _data = queryformRef?.current?.getFieldsValue()
            onQuery({...pageInfo,..._data})
        }
    }, [pageInfo.current,pageInfo.pageSize])

    const onQuery = async (_data: any) => {
        if (_data.createTime) {
            _data.params = {}
            _data.params['beginTime'] = _data.createTime[0];
            _data.params['endTime'] = _data.createTime[1];
            delete _data.createTime
        }

        layoutStore.OpenSpanning();
        listOnline(_data).then((res) => {
            setTableListDataSource(res.data)
            if (res.total) {
                setPageInfo({ ...pageInfo, total: res.total })
            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })

        return _data;
    }

    const onPageChange: (current: number, pageSize: number) => void = (current, pageSize) => {
        setPageInfo({ ...pageInfo, current, pageSize });
    };


    return (
        <PageDiv>
            <QueryFilter<SysUserOnlineDomain>
                defaultCollapsed
                split
                span={4}
                onFinish={(_data) => onQuery({ ...pageInfo, ..._data, current: 1, })}
                formRef={queryformRef}>
                <ProFormText key='ipaddr' name="ipaddr" label="登录地址" />
                <ProFormText key='userName' name="userName" label="用户名称" />
            </QueryFilter>
            <ResizeTable<SysUserOnlineDomain>
                rowKey={'tokenId'}
                dataSource={tableListDataSource}
                actionRef={actionRef}
                columns={columns}
                cardBordered
                revalidateOnFocus={false}
                pagination={{
                    ...pageInfo,
                    showTitle: false,
                    onChange: onPageChange
                }}
            >
            </ResizeTable>
        </PageDiv>

    )
}
export default Online;